<template>
  <div class="p-2">
    <div class="tabs-top-right">
      <el-button @click="goBack()">返 回</el-button>
    </div>
    <div style="display: inline-block;position: absolute;z-index: 999;padding: 0 10px;left: 20%;font-weight:500;line-height:40px;font-size:14px;"><span> {{ projectName }} </span></div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane v-if="showTab!=0" label="小区信息" name="1">
        <el-card shadow="never">
          <div class="card_top">
            <span class="card_title">{{title}}小区信息</span>
            <el-divider class="card_line_first" />
          </div>
          <div class="card_mian">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form ref="projectFormRef" :model="form" :rules="rules" label-width="120px">
                  <el-form-item label="小区名称" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="请输入小区名称" />
                  </el-form-item>
                  <el-form-item label="开始时间" prop="beginTime">
                    <el-date-picker
                      clearable
                      v-model="form.beginTime"
                      type="date"
                      value="YYYY-MM-DD"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="请选择开始时间"
                      style="width:100%;"
                      class="date-picker-width"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="小区负责人" prop="projectLeader">
                    <el-input v-model="form.projectLeader" placeholder="请输入小区负责人" />
                  </el-form-item>
                  <el-form-item label="负责人联系方式" prop="contactInformation">
                    <el-input v-model="form.contactInformation" placeholder="请输入小区负责人联系方式" />
                  </el-form-item>
                  <el-form-item label="是否撤场" prop="isExit" v-show="route.query.type === 'edit'">
                    <el-radio-group v-model="form.isExit">
                      <el-radio label="0" size="large">否</el-radio>
                      <el-radio label="1" size="large">是</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="固定资产总额" prop="assetTotal">
                    <el-input v-model="form.assetTotal" disabled />
                  </el-form-item>
                  <el-form-item label="非固定资产总额" prop="notAssetTotal">
                    <el-input v-model="form.notAssetTotal" disabled />
                  </el-form-item>
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                  </el-form-item>
                </el-form>
                <div class="card_footer">
                  <el-button type="primary" @click="submitForm">提 交</el-button>
                  <el-button @click="cancel">取 消</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane v-if="showTab==0" label="固定资产信息" name="2">
        <el-card shadow="never">
          <div class="card_mian">
            <div>
              <div class="card_top-tow">
                <span class="card_title">固定资产领用记录</span>
              </div>
              <div>
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @clear="handleQuery('1')" />
                  </el-form-item>
                  <el-form-item label="时间段">
                    <el-date-picker
                      v-model="dateRange"
                      value-format="YYYY-MM-DD"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="handleQuery('1')"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery('1')">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery('1')">重置</el-button>
                    <el-button type="warning" icon="Download" @click="handleExport('1')">导出表格</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <!-- <span>固定资产信息合计</span> -->
              <el-table ref="fixedAssetInfoListTableRef" v-loading="loading" :data="fixedAssetInfoList" border height="250">
                <el-table-column label="序号" type="index" width="52" align="center">
                  <template #default="scope">
                    <span>{{scope.$index+1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="类别" align="center" prop="categoryName"></el-table-column>
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="型号" align="center" prop="model" />
                <el-table-column label="单位" align="center" prop="unit" />
                <el-table-column label="数量" align="center" prop="outboundQuantity" />
                <el-table-column label="单价" align="center" prop="univalence" />
                <el-table-column label="时间" align="center" prop="outboundTime" width="180">
                  <!-- <template #default="scope">
                    <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
                  </template> -->
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top:40px;">
              <div class="card_top-tow">
                <span class="card_title">小区固定资产台账</span>
              </div>
              <div>
                <el-form :model="queryParamsLedger" ref="queryFormLedgerRef" :inline="true" label-width="68px">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="queryParamsLedger.name" placeholder="请输入名称" clearable style="width: 240px" @clear="handleQueryLedger('1')" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQueryLedger('1')">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQueryLedger('1')">重置</el-button>
                    <el-button type="warning" icon="Download" @click="handleExportLedger('1')">导出表格</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-table ref="fixedAssetInfoTotalListRef" v-loading="fixedAssetInfoTotalListLoading" :data="fixedAssetInfoTotal" border height="250">
                <el-table-column label="序号" type="index" width="52" align="center">
                  <template #default="scope">
                    <span>{{scope.$index+1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="类别" align="center" prop="category"></el-table-column>
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="型号" align="center" prop="model" />
                <el-table-column label="单位" align="center" prop="unit" />
                <el-table-column label="数量" align="center" prop="outboundQuantity" />
                <el-table-column label="合计" align="center" prop="total" />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane v-if="showTab==0" label="非固定资产信息" name="3">
        <el-card shadow="never">
          <div class="card_mian">
            <div>
              <div class="card_top-tow">
                <span class="card_title">非固定资产领用记录</span>
              </div>
              <div>
                <el-form :model="queryParamsNotFixed" ref="queryFormRef" :inline="true" label-width="68px">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="queryParamsNotFixed.name" placeholder="请输入名称" clearable style="width: 240px" @clear="handleQuery('2')" />
                  </el-form-item>
                  <el-form-item label="时间段">
                    <el-date-picker
                      v-model="dateRangeNotFixed"
                      value-format="YYYY-MM-DD"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      @change="handleQuery('2')"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery('2')">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery('2')">重置</el-button>
                    <el-button type="warning" icon="Download" @click="handleExport('2')">导出表格</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-table ref="notfixedAssetInfoListTableRef" v-loading="notfixedAssetInfoListLoading" :data="notfixedAssetInfoList" border height="250">
                <el-table-column label="序号" type="index" width="52" align="center">
                  <template #default="scope">
                    <span>{{scope.$index+1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="类别" align="center" prop="categoryName"></el-table-column>
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="型号" align="center" prop="model" />
                <el-table-column label="单位" align="center" prop="unit" />
                <el-table-column label="数量" align="center" prop="outboundQuantity" />
                <el-table-column label="单价" align="center" prop="univalence" />
                <el-table-column label="时间" align="center" prop="outboundTime" width="180">
                  <!-- <template #default="scope">
                    <span>{{ parseTime(scope.row.outboundTime, '{y}-{m}-{d}') }}</span>
                  </template> -->
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top:40px;">
              <div class="card_top-tow">
                <span class="card_title">小区非固定资产台账</span>
              </div>
              <div>
                <el-form :model="queryParamsNotFixedTotalLedger" ref="queryFormLedgerRef" :inline="true" label-width="68px">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="queryParamsNotFixedTotalLedger.name" placeholder="请输入名称" clearable style="width: 240px" @clear="handleQueryLedger('2')" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQueryLedger('2')">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQueryLedger('2')">重置</el-button>
                    <el-button type="warning" icon="Download" @click="handleExportLedger('2')">导出表格</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-table ref="notfixedAssetInfoTotalListRef" v-loading="notfixedAssetInfoTotalListLoading" :data="notfixedAssetInfoTotal" border height="250">
                <el-table-column label="序号" type="index" width="52" align="center">
                  <template #default="scope">
                    <span>{{scope.$index+1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="类别" align="center" prop="category"></el-table-column>
                <el-table-column label="名称" align="center" prop="name" />
                <el-table-column label="型号" align="center" prop="model" />
                <el-table-column label="单位" align="center" prop="unit" />
                <el-table-column label="数量" align="center" prop="outboundQuantity" />
                <el-table-column label="合计" align="center" prop="total" />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="projectAdd" lang="ts">
import { getProject,addProject,updateProject,listAssetOutboundRecordsTotal } from '@/api/business/project';
import { ProjectVO, ProjectQuery, ProjectForm } from '@/api/business/project/types';import { listAssetOutboundRecords } from '@/api/business/assetOutboundRecords/index';
import { listAssetCategory } from '@/api/business/assetCategory/index';

import router from "@/router";
import { formatDate } from '@/utils/index.ts'

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const projectFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const queryFormLedgerRef = ref<ElFormInstance>();
const fixedAssetInfoListTableRef = ref<ElFormInstance>();
const notfixedAssetInfoListTableRef = ref<ElFormInstance>();
const fixedAssetInfoTotalListRef = ref<ElFormInstance>();
const notfixedAssetInfoTotalListRef = ref<ElFormInstance>();

const activeName = ref('1')
const showTab = ref(0)
const title = ref("新增")
const loading = ref(false);
const fixedAssetInfoTotalListLoading = ref(false);
const notfixedAssetInfoListLoading = ref(false);
const notfixedAssetInfoTotalListLoading = ref(false);
const fixedAssetInfoList = ref([]);
const notfixedAssetInfoList = ref([]);
const fixedAssetInfoTotal = ref([]);
const notfixedAssetInfoTotal = ref([]);
const categoryData = ref([])
const dateRange = ref(['', '']);
const dateRangeNotFixed = ref(['', '']);
const fixedAssetInfoListNum = ref(0)
const notfixedAssetInfoListNum = ref(0)
const fixedAssetInfoTotalNum = ref(0)
const notfixedAssetInfoTotalNum = ref(0)
const projectName = ref('')

const initFormData: ProjectForm = {
  id: undefined,
  projectName: undefined,
  beginTime: undefined,
  projectLeader: undefined,
  contactInformation: undefined,
  remark: undefined,
  isExit:undefined,
}
const data = reactive<PageData<ProjectForm, ProjectQuery>>({
  form: {...initFormData},
  queryParams: {
    projectId:undefined,
    type:undefined,
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {
    }
  },
  queryParamsNotFixed: {
    projectId:undefined,
    type:undefined,
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {
    }
  },
  queryParamsLedger: {
    projectId:undefined,
    type:undefined,
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {
    }
  },
  queryParamsNotFixedTotalLedger: {
    projectId:undefined,
    type:undefined,
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "小区id不能为空", trigger: "blur" }
    ],
    projectName: [
      { required: true, message: "小区名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, queryParamsNotFixed, queryParamsLedger, queryParamsNotFixedTotalLedger, form, rules } = toRefs(data);

/** 取消按钮 */
const cancel = () => {
  reset();
  goBack()
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  projectFormRef.value?.resetFields();
}

/** 提交按钮 */
const submitForm = () => {
  projectFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateProject(form.value).then(() =>  proxy?.$modal.msgSuccess("修改成功"));
        await getProjectForm(form.value.id);
        await goBack()
      } else {
        await addProject(form.value).then(() =>  proxy?.$modal.msgSuccess("新增成功"));
        await goBack()
      }
    }
  });
}

const getDateRange = (params: any, dateRange: any[]) =>{
  const search = params;
  search.params = typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  search.beginTime = dateRange[0];
  search.endTime = dateRange[1];
  return search;
}

const getListAssetOutboundRecords = async (type) =>{
  if (type=="1") {
    loading.value = true
    queryParams.value.type = type
    const res = await listAssetOutboundRecords(getDateRange(queryParams.value, dateRange.value))
    fixedAssetInfoList.value = res.rows
    fixedAssetInfoListNum.value = res.total
    loading.value = false
  }else{
    notfixedAssetInfoListLoading.value = true
    queryParamsNotFixed.value.type = type
    const res = await listAssetOutboundRecords(getDateRange(queryParamsNotFixed.value, dateRangeNotFixed.value))
    notfixedAssetInfoList.value = res.rows
    notfixedAssetInfoListNum.value = res.total
    notfixedAssetInfoListLoading.value = false
  }
}

const getListAssetOutboundRecordsTotal = async (type) =>{
  if (type=="1") {
    fixedAssetInfoTotalListLoading.value = true
    queryParamsLedger.value.type = type
    const res = await listAssetOutboundRecordsTotal(queryParamsLedger.value)
    fixedAssetInfoTotal.value = res.rows
    fixedAssetInfoTotalNum.value = res.total
    fixedAssetInfoTotalListLoading.value = false
  }else{
    notfixedAssetInfoTotalListLoading.value = true
    queryParamsNotFixedTotalLedger.value.type = type
    const res = await listAssetOutboundRecordsTotal(queryParamsNotFixedTotalLedger.value)
    notfixedAssetInfoTotal.value = res.rows
    notfixedAssetInfoTotalNum.value = res.total
    notfixedAssetInfoTotalListLoading.value = false
  }
}

const getProjectForm = async (id) =>{
  const res = await getProject(id);
  Object.assign(form.value, res.data);
}

const getTableContent = async (id)=>{
  queryParams.value.projectId = queryParamsNotFixed.value.projectId = queryParamsNotFixedTotalLedger.value.projectId = queryParamsLedger.value.projectId = id
  await getListAssetOutboundRecords("1")
  await getListAssetOutboundRecordsTotal("1")
  await getListAssetOutboundRecords("2")
  await getListAssetOutboundRecordsTotal("2")
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/projectManagement/projectList" };
  proxy?.$tab.closeOpenPage(obj);
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event)
}

const getCategory = (data) =>{
  if (data && categoryData.value) {
    let obj = categoryData.value.find(item=>item.id ==data)
    return obj?.category
  }
}

const getCategoryData = async () =>{
  const res = await listAssetCategory();
  categoryData.value = res.rows
}

/** 重置按钮操作 */
const resetQuery = (type) => {
  if (type=="1") {
    dateRange.value = ['', ''];
  }else{
    dateRangeNotFixed.value = ['', ''];
  }
  queryFormRef.value?.resetFields();
  handleQuery(type)
}

/** 搜索按钮操作 */
const handleQuery = (type) => {
  if (type=="1") {
    queryParams.value.pageNum = 1;
  }else{
    queryParamsNotFixed.value.pageNum = 1;
  }
  getListAssetOutboundRecords(type)
}

/** 导出按钮操作 */
const handleExport = (type) => {
  let name
  if (type == '1') {
    queryParams.value.type = type
    name = "固定资产领用记录"
    proxy?.download('business/assetOutboundRecords/export/list', {
    ...getDateRange(queryParams.value, dateRange.value)
    }, `${name}_${formatDate(new Date().getTime())}.xlsx`)
  }else{
    queryParamsNotFixed.value.type = type
    name = "非固定资产领用记录"
    proxy?.download('business/assetOutboundRecords/export/list', {
    ...getDateRange(queryParamsNotFixed.value, dateRangeNotFixed.value)
    }, `${name}_${formatDate(new Date().getTime())}.xlsx`)
  }
}

/** --------------台账信息操作 */
/** 重置按钮操作 */
const resetQueryLedger = (type) => {
  queryFormLedgerRef.value?.resetFields();
  handleQueryLedger(type)
}

/** 搜索按钮操作 */
const handleQueryLedger = (type) => {
  if (type=="1") {
    queryParamsLedger.value.pageNum = 1;
  }else{
    queryParamsNotFixedTotalLedger.value.pageNum = 1;
  }
  getListAssetOutboundRecordsTotal(type)
}

/** 导出按钮操作 */
const handleExportLedger = (type) => {
  let name
  if (type == '1') {
    queryParamsLedger.value.type = type
    name = "小区固定资产台账"
    proxy?.download('business/assetOutboundRecords/export/total', {
    ...queryParamsLedger.value
    }, `${name}_${formatDate(new Date().getTime())}.xlsx`)
  }else{
    queryParamsNotFixedTotalLedger.value.type = type
    name = "小区非固定资产台账"
    proxy?.download('business/assetOutboundRecords/export/total', {
    ...queryParamsNotFixedTotalLedger.value
    }, `${name}_${formatDate(new Date().getTime())}.xlsx`)
  }

}

const handleScroll = (event) => {
  const tableBody = event.target;
  if (((tableBody.scrollHeight - tableBody.scrollTop)|0) <= tableBody.clientHeight && fixedAssetInfoList.value.length < fixedAssetInfoListNum.value) {
    loadMore('1');
  }
}
const handleScrollNotfixed = (event) => {
  const tableBody = event.target;
  if (((tableBody.scrollHeight - tableBody.scrollTop)|0) <= tableBody.clientHeight && notfixedAssetInfoList.value.length < notfixedAssetInfoListNum.value) {
    loadMore('2');
  }
}
const handleScrollFixedTotal = (event) => {
  const tableBody = event.target;
  if (((tableBody.scrollHeight - tableBody.scrollTop)|0) <= tableBody.clientHeight && fixedAssetInfoTotal.value.length < fixedAssetInfoTotalNum.value) {
    loadMoreTotal('1');
  }
}
const handleScrollNotFixedTotal = (event) => {
  const tableBody = event.target;
  if (((tableBody.scrollHeight - tableBody.scrollTop)|0) <= tableBody.clientHeight && notfixedAssetInfoTotal.value.length < notfixedAssetInfoTotalNum.value) {
    loadMoreTotal('2');
  }
}

const loadMore = async (type) => {
  if (loading.value) return;
  setTimeout(() => {
    if (type=='1') {
      loading.value = true
      queryParams.value.pageNum++
      queryParams.value.type = type
      listAssetOutboundRecords(getDateRange(queryParams.value, dateRange.value)).then((res) => {
        fixedAssetInfoList.value = fixedAssetInfoList.value.concat(res.rows);
        loading.value = false
      })
    }else{
      notfixedAssetInfoListLoading.value = true
      queryParamsNotFixed.value.pageNum++
      queryParamsNotFixed.value.type = type
      listAssetOutboundRecords(getDateRange(queryParamsNotFixed.value, dateRangeNotFixed.value)).then((res) => {
        notfixedAssetInfoList.value = notfixedAssetInfoList.value.concat(res.rows);
        notfixedAssetInfoListLoading.value = false
      })
    }
  }, 1000);
};

const loadMoreTotal = async (type) => {
  if (loading.value) return;
  setTimeout(() => {
    if (type=='1') {
      fixedAssetInfoTotalListLoading.value = true
      queryParamsLedger.value.pageNum++
      queryParamsLedger.value.type = type
      listAssetOutboundRecordsTotal(queryParamsLedger.value).then((res) => {
        fixedAssetInfoTotal.value = fixedAssetInfoTotal.value.concat(res.rows);
        fixedAssetInfoTotalListLoading.value = false
      })
    }else{
      notfixedAssetInfoTotalListLoading.value = true
      queryParamsNotFixedTotalLedger.value.pageNum++
      queryParamsNotFixedTotalLedger.value.type = type
      listAssetOutboundRecordsTotal(queryParamsNotFixedTotalLedger.value).then((res) => {
        notfixedAssetInfoTotal.value = notfixedAssetInfoTotal.value.concat(res.rows);
        notfixedAssetInfoTotalListLoading.value = false
      })
    }
  }, 1000);
};

onMounted(async () => {
  if (route.query.type === 'add' ) {
    showTab.value = 1
    title.value='新增'
    activeName.value = '1'
  }else if(route.query.type === 'edit') {
    showTab.value = 2
    title.value='修改'
    activeName.value = '1'
  }else{
    showTab.value = 0
    title.value=''
    activeName.value = '2'
  }
  if (route.query.id) {
    // await getCategoryData()
    if (showTab.value == 0) {
      projectName.value = route.query.projectName
      await getTableContent(route.query.id)
    }else{
      await getProjectForm(route.query.id)
    }
  }
  await nextTick(); // 确保表格渲染完毕
  const tableBodyWrapper = fixedAssetInfoListTableRef.value?.$el.querySelector('.el-scrollbar__wrap');
  if (tableBodyWrapper) {
    tableBodyWrapper.addEventListener('scroll', handleScroll);
  }
  const tableBodyWrapperNotFixed = notfixedAssetInfoListTableRef.value?.$el.querySelector('.el-scrollbar__wrap');
  if (tableBodyWrapperNotFixed) {
    tableBodyWrapperNotFixed.addEventListener('scroll', handleScrollNotfixed);
  }
  const tableBodyWrapperFixedTotal = fixedAssetInfoTotalListRef.value?.$el.querySelector('.el-scrollbar__wrap');
  if (tableBodyWrapperFixedTotal) {
    tableBodyWrapperFixedTotal.addEventListener('scroll', handleScrollFixedTotal);
  }
  const tableBodyWrapperNotFixedTotal = notfixedAssetInfoTotalListRef.value?.$el.querySelector('.el-scrollbar__wrap');
  if (tableBodyWrapperNotFixedTotal) {
    tableBodyWrapperNotFixedTotal.addEventListener('scroll', handleScrollNotFixedTotal);
  }
});
</script>

<style>
/* 标签页样式 */
.tabs-top-right {
  display: inline-block;
  position: absolute;
  right: 0;
  transform: translate(-15px, 5px);
  z-index: 999;
  padding: 0 10px;
}
.bottom-marker{
  height: 1px;
  background: transparent;
}
</style>
